const Topic = require('../models/topics')
const User = require('../models/users')
const Question = require('../models/questions')

class Topics {
  async find(ctx) {
    // 每页大小
    const pageSize = Math.max((ctx.query.page_size || 10) * 1, 1)
    // 当前页
    const current = ctx.query.current * 1
    // 偏移量
    const offset = Math.max(current - 1, 0) * pageSize
    // 查询参数
    const params = { name: new RegExp(ctx.query.q) }

    ctx.body = await Topic.find(params).limit(pageSize).skip(offset)
  }

  async findById(ctx) {
    const { fields = '' } = ctx.query
    // example: name;avatar_url;introducation ---> name avatar_url introducation
    const str = fields.replaceAll(';', ' ')
    const topic = await Topic.findById(ctx.params.id).select(str)
    ctx.body = topic
  }

  async create(ctx) {
    ctx.verifyParams({
      name: { type: 'string', required: true },
      avatar_url: { type: 'string', required: false },
      introducation: { type: 'string', required: false }
    })
    const topic = await new Topic(ctx.request.body).save()
    ctx.body = topic
  }

  async update(ctx) {
    ctx.verifyParams({
      name: { type: 'string', required: false },
      avatar_url: { type: 'string', required: false },
      introducation: { type: 'string', required: false }
    })
    const topic = await Topic.findByIdAndUpdate(
      ctx.params.id,
      ctx.request.body,
      // NOTE: 返回更新后的数据
      { new: true }
    )
    ctx.body = topic
  }

  async listFollowers(ctx) {
    const users = await User.find({ followingTopics: ctx.params.id })
    ctx.body = users
  }

  async listQuestions(ctx) {
    const question = await Question.find({ topics: ctx.params.id })
    ctx.body = question
  }
}

module.exports = new Topics()
